<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>IndexedDB</title>
  <link rel="stylesheet" href="./demo.css">
</head>

<body>
  <div id="app">
    <div class="btn" @click="addIndexedDB">IndexedDB存储</div>
    <div class="btn" @click="deleteIndexedDB">IndexedDB删除</div>
    <div class="btn" @click="closeIndexedDB">IndexedDB关闭</div>
    <div class="btn" @click="deleteData(1)">IndexedDB存储</div>
    <div class="btn" @click="getDataByKey(1)">IndexedDB获取</div>
    <div class="btn" @click="clearData">IndexedDB删除缓存空间</div>
  </div>
  <script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.min.js"></script>
  <script>
    let app = new Vue({
      el: '#app',
      data: {
        indexedDB: window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB,
        IDBKeyRange: window.IDBKeyRange || window.webkitIDBKeyRange, //键范围
        myDB: {
          name: 'school',
          version: 1,
          db: null,
          ojstore: {
            name: 'students', //存储空间表的名字
            keypath: 'id' //主键
          }
        },
        students: [{
          id: 1,
          name: 'xxx',
          age: 20
        }, {
          id: 2,
          name: 'yyy',
          age: 30
        }, {
          id: 3,
          name: 'zzz',
          age: 40
        }]
      },
      created() {
        this.initIndexedDB()
      },
      methods: {
        // 初始化
        initIndexedDB(callback) {
          let dbName = this.myDB.name
          let dbVersion = this.myDB.version
          let request = this.indexedDB.open(dbName, dbVersion)
          request.onerror = (e) => {
            console.log(e.currentTarget.error.message)
          }
          request.onsuccess = (e) => {
            this.myDB.db = e.target.result
            console.log(`成功建立并打开数据库:${this.myDB.name}, version:${dbVersion}`)
          }
          request.onupgradeneeded = (e) => {
            let db = e.target.result,
              transaction = e.target.transaction,
              store
            if (!db.objectStoreNames.contains(this.myDB.ojstore.name)) {
              //没有该对象空间时创建该对象空间
              store = db.createObjectStore(this.myDB.ojstore.name, {
                keyPath: this.myDB.ojstore.keypath
              })
              console.log(`成功建立对象存储空间:${this.myDB.ojstore.name}`)
            }
          }
        },
        // 删除
        deleteIndexedDB() {
          this.indexedDB.deleteDatabase(this.myDB.name)
          console.log(`${this.myDB.name}数据库已删除`)
        },
        // 关闭
        closeIndexedDB() {
          this.myDB.db.close()
          console.log(`数${this.myDB.db}据库已关闭`)
        },
        // 添加
        addIndexedDB() {
          //添加数据，重复添加会报错
          let store = this.myDB.db.transaction(this.myDB.ojstore.name, 'readwrite').objectStore(this.myDB.ojstore.name),
            request
          for (let item of this.students) {
            request = store.add(item)
            request.onerror = () => {
              console.error('add添加数据库中已有该数据')
            }
            request.onsuccess = () => {
              console.log('add添加数据已存入数据库')
            }
          }
        },
        //根据存储空间的键找到对应数据
        getDataByKey(key) {
          let store = this.myDB.db.transaction(this.myDB.ojstore.name, 'readwrite').objectStore(this.myDB.ojstore.name);
          let request = store.get(key);
          request.onerror = () => {
            console.error('getDataByKey error')
          }
          request.onsuccess = (e) => {
            let result = e.target.result
            console.log('查找数据成功')
            console.log(result)
          }
        },
        // 删除某一条记录
        deleteData(key) {
          let store = this.myDB.db.transaction(this.myDB.ojstore.name, 'readwrite').objectStore(this.myDB.ojstore.name)
          console.log(`已删除存储空间${this.myDB.ojstore.name}中${key}记录`)
        },
        // 删除缓存空间
        clearData() {
          let store = this.myDB.db.transaction(this.myDB.ojstore.name, 'readwrite').objectStore(this.myDB.ojstore.name)
          store.clear()
          console.log(`已删除存储空间${storename}全部记录`)
        }
      }
    })
  </script>
</body>

</html>